<?php
namespace Wechat\Controller;
use Think\Controller;

class IndexController extends Controller {
	
	private $appid;
	private $config;
	private $data;
	private $keyword;
	private $wechat;
	
	function _initialize() {
		$appid = I('get.appid');
		empty($appid) && exit('Access Denied!');
		$this->appid = $appid;
		//验证消息真实性
		if ($this->valid()) {
			//如果有echostr 说明是验证服务器归属权
			if (isset($_GET['echostr'])) {
				//记录服务器验证信息
				$model = M('WechatApp');
				$data['verified']    = 1;
				$data['verify_time'] = NOW_TIME;
				$model->where('id='.$this->appid)->save($data);
				exit($_GET['echostr']);
			}
			//响应次数-1
			self::appDec();
		}else {
			exit('Signature Error!');
		}
	}
	
	/**
	 * 重写的消息回复方法
	 */
	private function response($content) {
		$this->wechat->response($content);
	}
	/**
	 * 事件处理入口，处理各种事件
	 */
	function index($appid){
		if (IS_POST) {
		 	$this->wechat = new \Wechat\ORG\ThinkWechat();
		 	$this->data = $this->wechat->request();
		 	if (isset($this->data['Content'])) {
		 		$this->keyword = $this->data['Content'];
		 	}
			switch ($this->data['MsgType']) {
				case 'event' :
					$this->_event();
					break;
				case 'text' :
					$this->_text();
					break;
				case 'image' :
					break;
				case 'voice' :
					break;
				case 'video' :
					break;
				case 'location' :
					break;
				case 'link' :
					break;
				default : $this->_text();
			}
		}
	}
	
	/**
	 * 用来处理事件，如 关注事件，取消关注事件
	 */
	private function _event() {
		//关注事件
		if ($this->data['Event'] == 'subscribe') {
			//将用户增加到被关注的应用用户中
			$wechat = new \Member\ORG\Wechat($this->appid);
			$user = M('User');
			$data = $wechat->user($this->data['FromUserName']);
			$data['appid'] = $this->appid;
			$data['openid'] = $this->data['FromUserName'];
			$user->add($data);
			$map['appid'] = $this->appid;
			$content = M('ReplyAttention')->where($map)->getField('content');
			$this->response($content);
		}
		//取消关注
		if ($this->data['Event'] == 'unsubscribe') {
			$user = M('User');
			$map['openid'] = $this->data['FromUserName'];
			$map['appid']  = $this->appid;
			$user->where($map)->delete();
			exit;
		}
	}
	/**
	 * 处理用户发送的文本消息
	 */
	private function _text() {
		$AutoChat = new \Wechat\ORG\AutoChat();
		$keyword = (string)$this->keyword;
		$prefix  = mb_substr($keyword, 0, 2, 'utf-8');
		$keyStr  = mb_substr($keyword, 2, strlen($keyword), 'utf-8');
		$keyStr  = trim($keyStr);
		switch ($prefix) {
			case '天气' :
				$return = $AutoChat->wether($keyStr);
			break;
			case '留言' :
				$guestData['appid'] = $this->appid;
				$guestData['openid'] = $this->data['FromUserName'];
				$guestData['content'] = $keyStr;
				$guestData['create_time'] = NOW_TIME;
				if (M('Guestbook')->add($guestData)) {
					$return = '您的留言已经收到，感谢您的支持！';
				}else {
					$return = '留言系统出现故障，请稍候再试！';
				}
			break;
			case '网站' :
				$web = M('WebSite');
				$webmap['appid'] = $this->appid;
				$webmap['status'] = 1;
				$webres = $web->where($webmap)->find();
				if (!$webres) {
					$return = '网站暂时未开通！';
				}else {
					$return = '<a href="http://wx.xcl.net.cn/wap?site='.$this->appid.'">'.$webres['title'].'</a>';
				}
			break;
			default:
				$model = M('Reply');
				$map['appid'] = $this->appid;
				$map['keyword'] = $keyword;
				$reply = $model->where($map)->select();
				if ($reply) {
					shuffle($reply);
					$result = M('reply_'.$reply[0]['type'])->find($reply[0]['id']);
					$return = $result['content'];
				}else {
					$map2['appid'] = $this->appid;
					$result = M('ReplyUndefine')->where($map2)->find();
					if ($result['type'] == 'text') {
						$return = $result['content'];
					}else {
						$return = $AutoChat->chat($keyword, $result['type']);
					}
				}
		}
		if ($_GET['debug'] == 'true') {
			$runtime = number_format((microtime(TRUE) - $GLOBALS['_beginTime']), 4);
			$runtime = "\n".$runtime.'s';
		}else {
			$runtime = '';
		}
		$this->response($return.$runtime);
	}
	
	/**
	 * 调试模式，应用于正式的时候，应该去除
	 */
	private function debug() {
		if ($_GET['debug'] == 'true') {
			$model = M('WechatUrl');
			$model->url = $_SERVER['REQUEST_URI'];
			$model->create_time = NOW_TIME;
			$model->posts = $GLOBALS["HTTP_RAW_POST_DATA"]?:'';
			$model->ip = get_client_ip();
			$model->add();
			return true;
		}
	}
	/**
	 * 验证消息真实性
	 */
	private function valid() {
		if ($this->debug()) {
			return true;
		}
		$signature = $_GET['signature'];
		$timestamp = $_GET['timestamp'];
		$nonce     = $_GET['nonce'];
		if (empty($signature) || empty($timestamp) || empty($nonce)) {
			return false;
		}
		static $appList;
		/* 获取缓存数据 */
		empty($appList) && $appList = S('sys_app_list');
		$key = $this->appid;
		/* 已经缓存则直接使用缓存信息 */
		if (isset($appList[$key])) {
			$token = $appList[$key];
		}else {
			$model = M('WechatApp');
			$map['id'] = $this->appid;
			$token = $model->where($map)->getField('token');
			//赋值，并添加到缓存中去
			$appList[$key] = $token;
			$count = count($appList);
			$max   = C('USER_MAX_CACHE');
			while ($count-- > $max) {
				array_shift($appList);
			}
			S('sys_app_list', $appList);
		}
		if (!$token) return false;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode($tmpArr);
		return sha1($tmpStr) == $signature;
	}
    
    /**
     * 响应次数 -1
     */
    private function appDec() {
    	$map['appid'] = $this->appid;
    	$map['connect'] = array('gt', 0);
    	$dec = M('WechatQuota')->where($map)->setDec('connect');
    	if (!$dec) {
    		$this->response('此公众号响应次数已经用完！');
    	}
    }
}